package com.serviceprovider.business.module.admin.messages.controller;

//~--- non-JDK imports --------------------------------------------------------

import com.serviceprovider.business.module.admin.messages.model.Message;
import com.serviceprovider.business.module.admin.messages.serivces.dao.interfaces.IMessagesService;
import com.serviceprovider.business.module.admin.role.model.Role;
import com.serviceprovider.business.module.admin.role.services.dao.interfaces.IRoleService;
import com.serviceprovider.business.module.admin.user.services.dao.interfaces.IUserService;
import com.serviceprovider.business.module.common.Page;
import com.serviceprovider.business.module.user.model.impl.User;
import com.serviceprovider.business.utility.AppUtil;
import com.serviceprovider.business.utility.ApplicationConfigProperties;
import com.serviceprovider.business.utility.RequestConstants;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

//~--- JDK imports ------------------------------------------------------------

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class MessagesController {
    @Autowired
    private ApplicationConfigProperties applicationConfigProperties;
    @Autowired
    private IMessagesService            messageService;
    @Autowired
    private IRoleService                roleService;
    @Autowired
    private IUserService                userService;
    @Autowired
    @Qualifier("validator")
    private Validator                   validator;

    @RequestMapping(value = RequestConstants.MessagesRequest.LIST)
    public ModelAndView listMessages(HttpServletRequest req, HttpSession sess) {
        ModelAndView mav    = new ModelAndView(RequestConstants.MessagesRequest.VIEW_LIST);
        int          pageNo = 1;

        try {
            pageNo = Integer.parseInt(req.getParameter("pageNo"));
        } catch (NumberFormatException ex) {}

        int recordSize = applicationConfigProperties.getRecordSize("list.records.size");

        if (req.getParameter("pageNo") != null) {
            pageNo = Integer.parseInt(req.getParameter("pageNo"));
        }

        String        sortOrder  = (req.getParameter("sortOrder") == null)
                                   ? "asc"
                                   : req.getParameter("sortOrder");
        String        sortColumn = (req.getParameter("sortColumn") == null)
                                   ? "id"
                                   : req.getParameter("sortColumn");
        Page<Message> messages   = messageService.getAll(pageNo, recordSize, sortColumn, sortOrder);

        mav.addObject("messagesList", messages);

        return mav;
    }

    @RequestMapping(value = RequestConstants.MessagesRequest.MESSAGES)
    public ModelAndView listUserMessages(HttpServletRequest req, HttpSession sess) {
        ModelAndView mav = new ModelAndView(RequestConstants.MessagesRequest.VIEW_MESSAGES);

        System.out.println("getting messages");

        String       loginUserEmail = sess.getAttribute("loginUserEmail").toString();
        User         user           = userService.getByEmail(loginUserEmail);
        Role         role           = user.getRole();
        List<String> messages       = messageService.getAllForRole(role);

        messages.addAll(messageService.getAllForUser(user));
        mav.addObject("messages", messages);

        return mav;
    }

    @RequestMapping(
        value  = RequestConstants.MessagesRequest.CREATE,
        method = RequestMethod.GET
    )
    public ModelAndView enterCreate(HttpSession sess) {
        ModelAndView mav         = new ModelAndView(RequestConstants.MessagesRequest.VIEW_CREATE);
        Message      messageForm = new Message();

        messageForm.setExpiryDate("");
        messageForm.setActive(true);
        messageForm.setRoleId(-1);
        messageForm.setUserId(-1);
        mav.addObject("roleList", roleService.findAll());
        mav.addObject("userList", userService.findAll());
        mav.addObject("createMessage", messageForm);

        return mav;
    }

    @RequestMapping(
        value  = RequestConstants.MessagesRequest.CREATE,
        method = RequestMethod.POST
    )
    public ModelAndView submitCreate(@ModelAttribute("createMessage") Message form, BindingResult result) {
        validator.validate(form, result);

        if (result.hasErrors()) {
            ModelAndView mav   = new ModelAndView(RequestConstants.MessagesRequest.VIEW_CREATE);
            FieldError   error = (FieldError) result.getAllErrors().get(0);

            mav.addObject("errorList", result.getAllErrors());
            mav.addObject("roleList", roleService.findAll());
            mav.addObject("userList", userService.findAll());
            mav.addObject("createMessage", form);

            return mav;
        }

        messageService.insert(form);

        ModelAndView mav = new ModelAndView("redirect:" + RequestConstants.MessagesRequest.LIST);

        return mav;
    }

    @RequestMapping(
        value  = RequestConstants.MessagesRequest.DELETE,
        method = RequestMethod.POST
    )
    public ModelAndView create(HttpServletRequest req) {
        String ids = AppUtil.toCommaSeparatedString(req.getParameterValues("ids"));

        messageService.deleteMany(ids);

        ModelAndView mav = new ModelAndView("redirect:" + RequestConstants.MessagesRequest.LIST);

        return mav;
    }

    @RequestMapping(value = RequestConstants.MessagesRequest.EDIT)
    public ModelAndView view(HttpServletRequest req) {
        int id = 0;

        if (req.getParameter("id") != null) {
            id = Integer.parseInt(req.getParameter("id"));
        }

        ModelAndView mav     = new ModelAndView(RequestConstants.MessagesRequest.VIEW_CREATE);
        Message      message = messageService.getById(id);

        mav.addObject("roleList", roleService.findAll());
        mav.addObject("userList", userService.findAll());
        mav.addObject("createMessage", message);

        return mav;
    }

    @RequestMapping(
        value  = RequestConstants.MessagesRequest.EDIT,
        method = RequestMethod.POST
    )
    public ModelAndView enterEdit(@ModelAttribute("createMessage") Message form, BindingResult result) {
        validator.validate(form, result);

        if (result.hasErrors()) {
            ModelAndView mav = new ModelAndView(RequestConstants.MessagesRequest.VIEW_CREATE);

            mav.addObject("errorList", result.getAllErrors());
            mav.addObject("roleList", roleService.findAll());
            mav.addObject("userList", userService.findAll());
            mav.addObject("createMessage", form);

            return mav;
        }

        messageService.update(form);

        ModelAndView mav = new ModelAndView("redirect:" + RequestConstants.MessagesRequest.LIST);

        return mav;
    }
}



